<template>
  <basic-container class="production-page">
    <el-row :gutter="20">
      <el-col :span="8" style="min-width: 300px">
        <div class="bindLeft" v-loading="bindLeftLoading" element-loading-text="条码信息查找中，请稍后..." element-loading-spinner="el-icon-loading">
          <h2>基本信息</h2>
          <avue-form ref="barCodeForm" v-model="barCode" :option="barCodeOption" @reset-change="emptytChange" @submit="submit"> </avue-form>
          <el-button type="primary" size="small" style="float: right" icon="el-icon-unlock" @click="handleUnlock">调整</el-button>
        </div>
      </el-col>
      <el-col :span="16">
        <h2>序列号信息</h2>
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          v-model="formdata"
          ref="crud"
          @row-update="rowUpdate"
          @selection-change="selectionChange"
          @size-change="sizeChange"
          @on-load="onLoad"
        >
          <template slot="menu" slot-scope="{ row }">
            <el-button size="small" type="text" icon="el-icon-delete" @click="deleteConfig(row)">删除</el-button>
          </template>
        </avue-crud>
      </el-col>
    </el-row>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <!-- 操作日志 -->
    <operation-log ref="operationLog"></operation-log>
  </basic-container>
</template>
<script>
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { unpackingAdjust, unpackingAdjustInner, packingCreate } from '@/api/warehouse/packageIntegration';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters } from 'vuex';
import { getYearWeek, focusInput, showSuccessLog, showFailLog, showWarningLog } from '@/util/helpers';
import OperationLog from '@/components/operation-log/operation-log.vue';
import { number } from 'echarts/core';
export default {
  components: {
    commonModalTemplate
  },
  name: 'packageIntegration',
  data() {
    return {
      productId: '',
      barCode: {},
      barCodeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        column: [
          {
            label: '调整内容',
            prop: 'adjustType',
            type: 'radio',
            span: 24,
            value: 'PACK',
            rules: [
              {
                required: true,
                trigger: 'blur'
              }
            ],
            dicData: [
              {
                label: '内箱包装',
                value: 'PACK'
              },
              {
                label: '产品SN',
                value: 'PRODUCT'
              }
            ],
            control: (val, form) => {
              if (val == 'PACK') {
                return {
                  productNo: { display: false },
                  productNoRemove: { display: false },
                  innerPackNo: { display: true },
                  innerPackNoRemove: { display: true }
                };
              } else if (val == 'PRODUCT') {
                return {
                  productNo: { display: true },
                  productNoRemove: { display: true },
                  innerPackNo: { display: false },
                  innerPackNoRemove: { display: false }
                };
              }
            },
            change: ({ value }) => {
              if (value) {
                this.data = [];
                this.barCode.sequenceNumber = '';
                this.barCode.quantity = '';
                this.barCode.innerPackNo = '';
                this.barCode.productNo = '';
                this.barCode.innerPackNoRemove = '';
                this.barCode.productNoRemove = '';
              }
            }
          },
          {
            label: '包装条码',
            prop: 'sequenceNumber',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入包装条码',
                trigger: 'blur'
              }
            ],
            enter: (value) => {
              this.verifyPackId(value);
            }
          },
          {
            label: '包装数量',
            disabled: true,
            span: 24,
            prop: 'quantity'
          },
          {
            label: '添加内箱包装',
            prop: 'innerPackNo',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入包装条码',
                trigger: 'blur'
              }
            ],
            enter: (value) => {
              this.verifyPackIdThe(value, 'innerPackNo');
            }
          },
          {
            label: '添加产品SN',
            prop: 'productNo',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入产品SN',
                trigger: 'blur'
              }
            ],
            enter: (value) => {
              this.verifyPackIdThe(value, 'productNo');
            }
          },
          {
            label: '移除内箱包装',
            prop: 'innerPackNoRemove',
            span: 24,
            enter: (value) => {
              this.verifyPackDelete(value, 'innerPackNoRemove');
            }
          },
          {
            label: '移除产品SN',
            prop: 'productNoRemove',
            span: 24,
            enter: (value) => {
              this.verifyPackDelete(value, 'productNoRemove');
            }
          },
          {
            label: '打印机',
            prop: 'printerName',
            type: 'search',
            span: 24,
            row: true,
            disabled: true,
            appendClick: () => {
              this.openPrintersModal();
            },
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '标签模板',
            prop: 'labelTemplateName',
            type: 'search',
            span: 24,
            row: true,
            disabled: true,
            appendClick: () => {
              this.openLabelTemplateModal();
            },
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: [],
      formdata: {},
      query: {},
      bindLeftLoading: false,
      loading: false,
      selectionList: [],
      option: {
        height: 'calc(100vh - 550px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        menu: true,
        refreshBtn: false,
        columnBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '添加内箱包装/产品SN',
            prop: 'sequenceNumber'
          },
          {
            label: '移除内箱包装/产品SN',
            prop: 'sequenceNumberRemove'
          }
        ]
      },
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  created() {
    const adjustlateId = localStorage.getItem('adjustlateId');
    const adjustprinterId = localStorage.getItem('adjustprinterId');
    this.getPrint(adjustlateId, adjustprinterId);
  },
  computed: {
    ...mapGetters(['permission'])
  },
  methods: {
    getPrint(adjustlateId, adjustprinterId) {
      if (adjustlateId) {
        let arr = JSON.parse(adjustlateId);
        this.barCode.labelTemplateId = arr.labelTemplateId;
        this.barCode.labelTemplateName = arr.labelTemplateName;
      }
      if (adjustprinterId) {
        let arrTo = JSON.parse(adjustprinterId);
        this.barCode.printerId = arrTo.printerId;
        this.barCode.printerName = arrTo.printerName;
      }
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      console.log(111);
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: `/api/mes-admin/labeltemplate/page?type=material&subType=work_in_progress&status=1`,
        isPage: true,
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '模版名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '模版代码',
            prop: 'code',
            search: true
          },
          {
            label: '客户/供应商',
            prop: 'clientName'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    getSelectedRows(rowData, title) {
      switch (this.modalName) {
        case 'labelTemplateModal':
          this.barCode.labelTemplateId = rowData.id;
          this.barCode.labelTemplateName = rowData.fileName;
          localStorage.setItem(
            'adjustlateId',
            JSON.stringify({
              labelTemplateId: rowData.id,
              labelTemplateName: rowData.fileName
            })
          );
          break;
        case 'printersModal':
          this.barCode.printerId = rowData.id;
          this.barCode.printerName = rowData.name;
          localStorage.setItem(
            'adjustprinterId',
            JSON.stringify({
              printerId: rowData.id,
              printerName: rowData.name
            })
          );
          break;
        default:
          break;
      }
    },
    // 条码条码回车
    verifyPackId(value) {
      let Obj = {
        packNo: value,
        adjustType: this.barCode.adjustType
      };
      unpackingAdjust(Obj)
        .then((res) => {
          showSuccessLog(res.data.msg);
          this.barCode.quantity = res.data.data.quantity;
        })
        .catch((error) => {
          showFailLog(error.data.msg);
        });
    },
    // 添加包装条码/产品SN
    verifyPackIdThe(value, type) {
      let judgment = false;
      this.data.forEach((element) => {
        if (element.sequenceNumber == value) {
          judgment = true;
        }
      });
      if (judgment) {
        this.$message.warning('请勿重复添加包装条码/产品SN');
        this.barCode.innerPackNo = '';
        this.barCode.productNo = '';
        return;
      }
      let paramMap = {
        packNo: this.barCode.sequenceNumber,
        adjustType: this.barCode.adjustType
      };
      if (type == 'innerPackNo') {
        paramMap['innerPackNo'] = value;
      } else {
        paramMap['productNo'] = value;
      }
      unpackingAdjustInner(paramMap)
        .then((res) => {
          if (res.data.data == true) {
            this.$confirm(res.data.msg, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              showSuccessLog('操作成功');
              this.data.push({ sequenceNumber: value, typeInfo: 'add' });
            });
          } else {
            showSuccessLog(res.data.msg);
            this.data.push({ sequenceNumber: value, typeInfo: 'add' });
          }
        })
        .catch((error) => {
          showFailLog(error.data.msg);
        });

      setTimeout(() => {
        this.barCode.innerPackNo = '';
        this.barCode.productNo = '';
        judgment = false;
      }, 500);
    },
    // 移除包装条码/产品SN
    verifyPackDelete(value, type) {
      let judgment = false;
      this.data.forEach((element) => {
        if (element.sequenceNumberRemove == value) {
          judgment = true;
        }
      });
      if (judgment) {
        this.$message.warning('请勿重复移除包装条码/产品SN');
        this.barCode.innerPackNoRemove = '';
        this.barCode.productNoRemove = '';
        return;
      }
      let paramMap = {
        packNo: this.barCode.sequenceNumber,
        adjustType: this.barCode.adjustType
      };
      if (type == 'innerPackNoRemove') {
        paramMap['innerOutPackNo'] = value;
      } else {
        paramMap['productOutNo'] = value;
      }
      unpackingAdjustInner(paramMap)
        .then((res) => {
          if (res.data.data == true) {
            this.$confirm(res.data.msg, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              showSuccessLog('操作成功');
              this.data.push({ sequenceNumberRemove: value, typeInfo: 'remove' });
            });
          } else {
            showSuccessLog(res.data.msg);
            this.data.push({ sequenceNumberRemove: value, typeInfo: 'remove' });
          }
        })
        .catch((error) => {
          showFailLog(error.data.msg);
        });

      setTimeout(() => {
        this.barCode.innerPackNoRemove = '';
        this.barCode.productNoRemove = '';
        judgment = false;
      }, 500);
    },
    deleteConfig(row) {
      console.log(row, 'row');
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.data.splice(row.$index, 1);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      });
    },
    handleUnlock() {
      if (this.data.length === 0) {
        this.$message.warning('请添加包装再调整');
        return;
      }
      this.$confirm('是否调整?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let add = [];
        let remove = [];
        this.data.forEach((element) => {
          if (element.typeInfo == 'add') {
            add.push(element.sequenceNumber);
          } else {
            remove.push(element.sequenceNumberRemove);
          }
        });
        let list = {
          packNo: this.barCode.sequenceNumber,
          adjustType: this.barCode.adjustType,
          labelTemplateId: this.barCode.labelTemplateId,
          equipmentId: this.barCode.printerId
        };
        if (this.barCode.adjustType == 'PACK') {
          list['innerPackNos'] = add;
          list['innerOutPackNos'] = remove;
        } else {
          list['productNos'] = add;
          list['productOutNos'] = remove;
        }
        console.log(list, 'list');
        packingCreate(list)
          .then((res) => {
            showSuccessLog(res.data.msg);
            this.barCode.sequenceNumber = '';
            this.barCode.quantity = '';
            this.barCode.innerPackNo = '';
            this.barCode.productNo = '';
            this.barCode.innerPackNoRemove = '';
            this.barCode.productNoRemove = '';
            this.barCode = {};
            this.data = [];
          })
          .catch((error) => {
            showFailLog(error.data.msg);
          });
      });
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss" scoped>
.packagingUnbindingPage {
  display: flex;
  .bindLeft {
    width: 20%;
    min-width: 300px;
    margin-right: 20px;
  }
  .bindRight {
    flex: 1;
  }
}
::v-deep .el-card .is-never-shadow {
  padding: 0 !important;
}
</style>
